<template>
    <div class="factory-wrapper">
        <IHeader class="header" back="true" title="打版" publish="true"></IHeader>
        <scroller class="material-content">
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="客户地区" :error="materialForm.area.error"></Label>
                <input v-model="materialForm.area.value" class="write enterpriseName" placeholder="请输入产品销售地区" type="text">
            </div>
            <div class="info-cell flex_row border-bottom-ebebeb moreSelect-line" @click="handleServiceSelect">
                <Label content="打版款式" :error="materialForm.styleType.error"></Label>
                <div class="handleChoose flex_row">
                    <text class="fs_28" :class="[materialForm.styleType.value === '请选择' ? 'col_cecece' : 'col_464646']">{{materialForm.styleType.value}}</text>
                    <image class="arrow_right_small" :src="imgPath('arrow_right_small.png')"></image>
                </div>
                <GridSelect v-if="styleSelectShow" class="moreSelect-wrapper" :list="allList.styleType" :limit="3" :cols="3"
                            :customStyles="customStyles" @overLimit="onOverLimit" @select="selectOver"></GridSelect>
            </div>
            <div class="info-cell flex_row moreSelect-line border-bottom-ebebeb">
                <Label content="增值需求"></Label>
                <div class="handleChoose flex_row padding_right_44">
                    <Radio v-for="(item, index) in otherDemand" :class="[index !== 0 ? 'margin_left_50' : '']" @doclick="handleOtherDemand(item)" :check="materialForm.addValueDemand.value === item" :key="index" :word="item"></Radio>
                </div>
                <text class="realSceneTip" v-if="materialForm.addValueDemand.value !== '无需求'">提示：请在下列描述信息中注明打样号码、工艺要求等</text>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="打版号码" :error="materialForm.editionNumber.error"></Label>
                <input v-model="materialForm.editionNumber.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="数量" :error="materialForm.number.error"></Label>
                <input v-model="materialForm.number.value" class="write enterpriseName" placeholder="请输入" type="number">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb" @click="handleSelectType">
                <Label content="数量单位" :error="materialForm.countType.error"></Label>
                <div class="handleChoose flex_row">
                    <text class="fs_28" :class="[materialForm.countType.value === '请选择' ? 'col_cecece' : 'col_464646']">{{materialForm.countType.value}}</text>
                    <image class="arrow_right_small" :src="imgPath('arrow_right_small.png')"></image>
                </div>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="费用" notnecessary="true" disable="true"></Label>
                <text class="orderNumber enterpriseName col_cecece">此项由泳衣库工作人员填写</text>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb" @click="handleSelectDate('deliveryDate')">
                <Label content="交货日期" :error="materialForm.deliveryDate.error"></Label>
                <div class="handleChoose flex_row">
                    <text class="fs_28" :class="[materialForm.deliveryDate.value === '请选择' ? 'col_cecece' : 'col_464646']">{{materialForm.deliveryDate.value}}</text>
                    <image class="arrow_right_small" :src="imgPath('arrow_right_small.png')"></image>
                </div>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="联系人" :error="materialForm.contact.error"></Label>
                <input v-model="materialForm.contact.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="联系地址" :error="materialForm.contactAddress.error"></Label>
                <input v-model="materialForm.contactAddress.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="联系人电话" :error="materialForm.contactPhone.error"></Label>
                <input v-model="materialForm.contactPhone.value" @blur="checkPhone" class="write enterpriseName" placeholder="请输入" type="tel">
            </div>
            <div class="info-cell border-bottom-ebebeb introduce-wrapper">
                <Label content="描述信息" :error="materialForm.introduction.error"></Label>
                <textarea class="enterpriseIntroduce" v-model="materialForm.introduction.value" placeholder="请说明打版要求及其他服务（需要打样，请说明打样要求，如：号码、工艺等）" maxlength="500"></textarea>
                <text class="word-number">{{countWord + '/500'}}</text>
            </div>
            <div class="info-cell border-bottom-ebebeb no-single">
                <div class="flex_row">
                    <Label content="图片上传" :error="materialForm.dataUpload.error"></Label>
                    <Question @doclick="handleUploadTip"></Question>
                </div>
                <text class="realSceneTip" v-if="uploadTip">如需上传文件请发送邮件至yyk@sina.com，并注明订单编号</text>
                <div class="image-container flex_row">
                    <div class="image-content flex_row" v-if="materialForm.dataUpload.value.length > 0">
                        <div class="image-box" :class="[(index !== 0) ? 'margin_left_12' : '']" v-for="(item, index) in materialForm.dataUpload.value" :key="index">
                            <image class="scene-image" :src="item"></image>
                            <image class="delete-image" :src="imgPath('image_delete.png')" @click="handleDeleteImage(index)"></image>
                        </div>
                    </div>
                    <Uploader @doclick="handleUploadImage" v-if="materialForm.dataUpload.value.length < 3"></Uploader>
                </div>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb" @click="handleSelectDate('taskDate')">
                <Label content="任务有效期" :error="materialForm.taskDate.error"></Label>
                <div class="handleChoose flex_row">
                    <text class="fs_28" :class="[materialForm.taskDate.value === '请选择' ? 'col_cecece' : 'col_464646']">{{materialForm.taskDate.value}}</text>
                    <image class="arrow_right_small" :src="imgPath('arrow_right_small.png')"></image>
                </div>
            </div>
            <Buttons class="nextStep" word="发布" @doclick="handleNextStep"></Buttons>
        </scroller>
        <!--数量单位弹窗-->
        <wxc-popup popup-color="#fff" :show="typeSelectShow" pos="right">
            <div class="dialog-content">
                <IHeader class="header" back="true" close="true" title="选择数量单位" @closeDialog="closeTypeDialog"></IHeader>
                <list class="enterprise-list">
                    <cell class="enterprise-item" @click="chooseThisMaterial(item, index)" v-for="(item, index) in allList.countType" :key="index">
                        <text class="enterprise-name item-height col_464646" :class="[(index === allList.countType.length - 1) ? '' : 'border-bottom-cecece']">{{item}}</text>
                    </cell>
                </list>
            </div>
        </wxc-popup>
        <!--错误弹窗-->
        <Modal :show="modalShow" :word="modalWord" type="0"></Modal>
        <!--loading-->
        <wxc-loading :show="loadingShow" :need-mask="needMask"></wxc-loading>
    </div>
</template>

<script>
import IHeader from '@/components/header'
import Label from '@/components/label'
import Question from '@/components/question'
import Uploader from '@/components/imageUpload'
import Buttons from '@/components/buttons'
import Radio from '@/components/radio'
import Modal from '@/components/modal'
import GridSelect from '@/components/grid-select'
import { WxcPopup, WxcLoading } from 'weex-ui'
import { validatenull, validatePhone, isvalidatemobile } from '@/util/validate'
import { submitEdition, editEdition, getWorkshopDetail } from '@/api/market'
import { fileUpload } from '@/api/common'
import Nat from 'natjs'

const modal = weex.requireModule('modal')
const picker = weex.requireModule('picker')

export default {
  name: 'edition',
  data () {
    return {
      id: '', // 任务id
      extId: '', // 发布id
      loadingShow: false, // loading
      needMask: true,
      imageIndex: 0, // 上传下标
      modalShow: false, // 显示错误弹窗
      modalWord: '', // 弹窗提示
      typeSelectShow: false, // 数量单位弹窗显示
      styleSelectShow: false, // 打版样式多选显示
      allList: {
        styleType: [{'title': '比基尼'}, {'title': '分体'}, {'title': '连体'}, {'title': '男士泳裤'}, {'title': '大码装'}, {'title': '童装'}, {'title': '其他'}], // 产品类型
        countType: ['件', '套'] // 数量单位类型
      }, // 类型列表
      materialForm: { // 布料表单
        // orderNumber: '', // 订单编号
        area: {
          value: '',
          name: '客户地区',
          error: false
        }, // 客户地区
        styleType: {
          value: '请选择',
          name: '打版样式',
          error: false
        }, // 打版样式
        addValueDemand: {
          value: '无需求',
          name: '增值需求',
          error: false
        }, // 增值需求
        editionNumber: {
          value: '',
          name: '打版号码',
          error: false
        }, // 打版号码
        number: {
          value: '',
          name: '数量',
          error: false
        }, // 数量
        countType: {
          value: '请选择',
          name: '数量单位',
          error: false
        }, // 数量单位
        deliveryDate: {
          value: '请选择',
          name: '交货日期',
          error: false
        }, // 交货日期
        contact: {
          value: '',
          name: '联系人',
          error: false
        }, // 联系人
        contactAddress: {
          value: '',
          name: '联系人地址',
          error: false
        }, // 联系人地址
        contactPhone: {
          value: '',
          name: '联系人电话',
          error: false
        }, // 联系人电话
        introduction: {
          value: '',
          name: '描述信息',
          error: false
        }, // 说明,
        dataUpload: {
          value: [],
          name: '图片上传',
          error: false
        }, // 资料上传
        taskDate: {
          value: '请选择',
          name: '任务有效期',
          error: false
        } // 任务有效期
      },
      customStyles: { // 多选样式
        height: '56px',
        fontSize: 28
      },
      otherDemand: ['做样', '无需求'], // 增值需求
      uploadTip: false // 上传文件提示
    }
  },
  computed: {
    countWord () {
      return this.materialForm.introduction.value.length
    }
  },
  created () {
    const that = this
    that.id = that.$route.query.id
    that.extId = that.$route.query.extId
    if (validatenull(that.id)) {
      return
    }
    that.loadingShow = true
    that.$api.get(getWorkshopDetail + that.id, {}, (res) => {
      let dataObj = res.data
      that.materialForm.area.value = dataObj.yykPlayVersion.clientArea
      that.materialForm.styleType.value = dataObj.yykPlayVersion.style
      that.materialForm.addValueDemand.value = dataObj.yykPlayVersion.addValueDemand
      that.materialForm.editionNumber.value = dataObj.yykPlayVersion.versionNumber
      that.materialForm.number.value = dataObj.yykPlayVersion.number
      that.materialForm.countType.value = dataObj.yykPlayVersion.numberUnit
      that.materialForm.deliveryDate.value = dataObj.yykPlayVersion.deliveryDate
      that.materialForm.contact.value = dataObj.yykPlayVersion.contact
      that.materialForm.contactPhone.value = dataObj.yykPlayVersion.contactPhone
      that.materialForm.contactAddress.value = dataObj.yykPlayVersion.contactAddress
      that.materialForm.introduction.value = dataObj.yykPlayVersion.describtion
      that.materialForm.taskDate.value = dataObj.yykPlayVersion.taskValidity
      let images = dataObj.yykPlayVersion.dataUpload.split(',')
      images.forEach((item) => {
        that.materialForm.dataUpload.value.push(item)
      })
      that.loadingShow = false
    })
  },
  methods: {
    handleServiceSelect () { // 打版样式显示开关
      this.styleSelectShow = !this.styleSelectShow
    },
    selectOver (item) { // 多选选中
      let list = item.checkedList
      let str = ''
      list.forEach((item) => {
        str += item.title + '、'
      })
      str = str.substring(0, str.length - 1)
      this.materialForm.styleType.value = str
    },
    onOverLimit (limit) {
      modal.toast({
        message: `最多选择${limit}个`,
        duration: 0.8
      })
    },
    handleOtherDemand (item) { // 增值需求切换
      this.materialForm.addValueDemand.value = item
    },
    handleSelectType () { // 数量单位弹窗显示
      this.typeSelectShow = true
    },
    closeTypeDialog () { // 关闭弹窗
      this.typeSelectShow = false
    },
    chooseThisMaterial (name, inx) { // 数量单位选择
      this.materialForm.countType.value = name
      // this.materialForm.countType.type = inx
      this.typeSelectShow = false
    },
    checkPhone () { // 验证联系人电话
      const that = this
      if (!validatePhone(that.materialForm.contactPhone.value).result && !isvalidatemobile(that.materialForm.contactPhone.value).result) {
        that.modalShow = true
        that.modalWord = that.materialForm.contactPhone.name + '信息有误'
        that.materialForm.contactPhone.error = true
        setTimeout(() => {
          that.modalShow = false
        }, 2000)
        return
      }
      that.materialForm.contactPhone.error = false
    },
    handleSelectDate (type) { // 选择时间
      const that = this
      let date = '' // 日期
      let time = '' // 时间
      picker.pickDate({
        value: date
      }, e => {
        if (e.result === 'success') {
          date = e.data
          setTimeout(() => {
            picker.pickTime({
              value: time
            }, event => {
              if (event.result === 'success') {
                time = event.data
                for (let i in that.materialForm) {
                  if (type === i) {
                    that.materialForm[i].value = date + ' ' + time + ':00'
                  }
                }
              }
            })
          }, 100)
        }
      })
    },
    handleUploadTip () { // 文件上传提示显示
      this.uploadTip = !this.uploadTip
    },
    uploadImage (list) { // 上传动作
      const that = this
      if (that.imageIndex >= list.length) {
        return
      }
      that.loadingShow = true
      Nat.upload(that.$api.url + fileUpload, {
        path: list[that.imageIndex]
      }, (errs, res) => {
        if (errs) {
          modal.toast({
            message: '[ERROR] ' + JSON.stringify(errs)
          })
          return
        }
        if (res.ok) {
          let data = JSON.parse(res.data)
          let imageUrl = data.data
          that.materialForm.dataUpload.value.push(imageUrl)
          that.loadingShow = false
          that.imageIndex++
          that.uploadImage(list)
        }
      })
    },
    handleUploadImage () { // 图片上传
      const that = this
      Nat.image.pick({
        limit: 3,
        showCamera: true
      }, (err, ret) => {
        if (err) {
          modal.toast({
            message: '[ERROR] ' + JSON.stringify(err)
          })
          return
        }
        that.loadingShow = true
        let paths = ret.paths
        that.imageIndex = 0
        that.uploadImage(paths)
      })
    },
    handleDeleteImage (inx) { // 删除图片
      const that = this
      that.materialForm.dataUpload.value.splice(inx, 1)
    },
    handleNextStep () { // 发布
      const that = this
      for (let i in that.materialForm) {
        if (!validatenull(that.materialForm[i].name)) {
          if (that.materialForm[i].error || validatenull(that.materialForm[i].value) || that.materialForm[i].value === '请选择') {
            that.modalShow = true
            that.modalWord = that.materialForm[i].name + '信息有误'
            that.materialForm[i].error = true
            setTimeout(() => {
              that.modalShow = false
              that.materialForm[i].error = false
            }, 2000)
            return
          }
        }
      }
      let nowTime = that.getNowDate()
      if (that.materialForm.deliveryDate.value < nowTime || that.materialForm.taskDate.value < nowTime) {
        modal.toast({
          message: '选择时间不能比当前时间早'
        })
        return
      }
      if (that.materialForm.deliveryDate.value < that.materialForm.taskDate.value) {
        modal.toast({
          message: '交货日期不能比任务有效期早'
        })
        return
      }
      let params = {
        clientArea: that.materialForm.area.value,
        style: that.materialForm.styleType.value,
        addValueDemand: that.materialForm.addValueDemand.value,
        versionNumber: that.materialForm.editionNumber.value,
        number: that.materialForm.number.value,
        numberUnit: that.materialForm.countType.value,
        deliveryDate: that.materialForm.deliveryDate.value,
        contact: that.materialForm.contact.value,
        contactPhone: that.materialForm.contactPhone.value,
        contactAddress: that.materialForm.contactAddress.value,
        describtion: that.materialForm.introduction.value,
        dataUpload: that.materialForm.dataUpload.value.join(','),
        taskValidity: that.materialForm.taskDate.value
      }
      let url = validatenull(that.id) ? submitEdition : editEdition
      if (!validatenull(that.id)) {
        params.id = that.extId
      }
      that.loadingShow = true
      that.$api.post(url, params, () => {
        that.loadingShow = false
        modal.toast({
          message: '发布成功'
        })
        setTimeout(() => {
          that.$router.push('/mine/myPublic')
        }, 500)
      }, () => {
        that.loadingShow = false
      }, true)
    }
  },
  components: {
    IHeader,
    Modal,
    Label,
    WxcPopup,
    WxcLoading,
    Buttons,
    GridSelect,
    Question,
    Radio,
    Uploader
  }
}
</script>

<style scoped>
    .col_cecece {
        color: #cecece;
    }
    .col_464646 {
        color: #464646;
    }
    .flex_row {
        flex-direction: row;
    }
    .fs_28 {
        font-size: 28px;
    }
    .border-bottom-cecece {
        border-bottom-width: 1px;
        border-bottom-style: solid;
        border-bottom-color: #cecece;
    }
    .border-bottom-ebebeb {
        border-bottom-width: 1px;
        border-bottom-style: solid;
        border-bottom-color: #ebebeb;
    }
    .item-height {
        height: 88px;
        line-height: 88px;
    }
    .material-content {
        padding-top: 100px;
        /*background-color: #f5f5f5;*/
    }
    .info-cell {
        padding-left: 24px;
        padding-right: 24px;
        justify-content: space-between;
    }
    .content-tit {
        padding-left: 24px;
        padding-right: 24px;
        color: #a4a4a4;
        font-size: 28px;
        background-color: #fff;
    }
    .handleChoose {
        align-items: center;
    }
    .margin_left_50 {
        margin-left: 50px;
    }
    .padding_right_44 {
        padding-right: 44px;
    }
    .arrow_right_small {
        width: 27px;
        height: 28px;
        margin-left: 16px;
    }
    .enterprise-item {
        padding-left: 24px;
        padding-right: 24px;
    }
    .enterprise-name {
        font-size: 28px;
    }
    .orderNumber {
        /*padding-right: 44px;*/
        line-height: 88px;
        text-align: right;
        font-size: 28px;
    }
    .write {
        /*padding-right: 44px;*/
        text-align: right;
        border-width: 0px;
        font-size: 28px;
        color: #464646;
        placeholder-color: #cecece;
    }
    .enterpriseName {
        width: 480px;
        lines: 1;
    }
    .enterpriseIntroduce {
        width: 654px;
        height: 200px;
        margin-top: 16px;
        margin-left: 24px;
        padding-top: 16px;
        padding-right: 16px;
        padding-bottom: 16px;
        padding-left: 16px;
        border-width: 1px;
        border-style: solid;
        border-color: #ebebeb;
        font-size: 24px;
        placeholder-color: #cecece;
    }
    .introduce-wrapper {
        padding-top: 20px;
        border-bottom-width: 0px;
    }
    .word-number {
        flex: 1;
        padding-right: 24px;
        font-size: 24px;
        line-height: 64px;
        color: #cecece;
        text-align: right;
    }
    .realSceneTip {
        width: 702px;
        height: 60px;
        margin-top: 20px;
        padding-left: 16px;
        padding-right: 16px;
        border-width: 1px;
        border-style: solid;
        border-color: #ff0f37;
        color: #ff0f37;
        font-size: 22px;
        line-height: 58px;
        border-radius: 4px;
    }
    .no-single {
        padding-top: 20px;
        padding-bottom: 24px;
        flex-wrap: wrap;
        justify-content: flex-start;
    }
    .image-container {
        width: 702px;
        margin-top: 20px;
    }
    .margin_left_12 {
        margin-left: 12px;
    }
    .image-content {
        margin-right: 12px;
    }
    .scene-image {
        width: 226px;
        height: 226px;
    }
    .delete-image {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 36px;
        height: 36px;
    }
    .nextStep {
        margin-top: 98px;
        margin-bottom: 144px;
    }
    .moreSelect-list {
        padding-top: 120px;
        padding-left: 16px;
        padding-right: 16px;
    }
    .enterprise-list {
        min-height: 700px;
        margin-top: 88px;
    }
    .moreSelect-line {
        padding-top: 24px;
        padding-bottom: 24px;
        flex-wrap: wrap;
    }
    .moreSelect-wrapper {
        width: 702px;
        margin-top: 20px;
        padding-top: 16px;
        padding-right: 16px;
        padding-bottom: 16px;
        padding-left: 16px;
        background-color: #ebebeb;
        border-radius: 10px;
        flex-wrap: wrap;
        /*justify-content: space-between;*/
    }
</style>
